package yslog

import (
	"context"
	"fmt"
	"gitee.com/kmyss/gf-ex/ysutils"
	"github.com/gogf/gf/v2/container/gmap"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/glog"
	"github.com/gogf/gf/v2/text/gstr"
)

var (
	localInstances       = gmap.NewStrAnyMap(true)
	configNodeNameLogger = "logger"
)

func Log(name ...string) *glog.Logger {

	var (
		ctx          = context.Background()
		instanceName = glog.DefaultName
	)
	if len(name) > 0 && name[0] != "" {
		instanceName = name[0]
	}

	return localInstances.GetOrSetFuncLock(instanceName, func() interface{} {
		l := g.Log().Clone()
		l.SetPrefix(fmt.Sprintf("[%s]", instanceName))

		// 开始寻找日志的配置，可以是级联的配置
		var (
			tmp      []string
			logKey   = fmt.Sprintf("%s.%s", configNodeNameLogger, instanceName)
			localKey = instanceName
			ok       = false
		)

		// 先读取 logger 在节点下的情况
		for len(localKey) != 0 && !ok {
			if cfgMap := ysutils.GetMapFromCfg(ctx, localKey+"."+configNodeNameLogger); cfgMap != nil {
				setConfig(l, cfgMap)
				ok = true
			} else {
				tmp = gstr.Split(localKey, ".")
				localKey = gstr.Join(tmp[0:len(tmp)-1], ".")
			}
		}

		// 去取 logger 在节点内的情况
		for len(logKey) != 0 && !ok {
			if cfgMap := ysutils.GetMapFromCfg(ctx, logKey); cfgMap != nil {
				setConfig(l, cfgMap)
				break
			} else {
				tmp = gstr.Split(logKey, ".")
				logKey = gstr.Join(tmp[0:len(tmp)-1], ".")
			}
		}

		if !ok {
			setConfig(l, g.MapStrAny{
				"level": "info",
			})
		}

		return l
	}).(*glog.Logger)

}

func setConfig(l *glog.Logger, cfgMap g.MapStrAny) {
	if err := l.SetConfigWithMap(cfgMap); err != nil {
		panic(err)
	}
}
